﻿<%@ WebHandler Language="C#" Class="baseToImg" %>


using System;
using System.Web;
using System.Text;
using System.IO;
using System.Drawing;

public class baseToImg : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.ContentEncoding = Encoding.UTF8;
        if (context.Request["REQUEST_METHOD"] == "OPTIONS")
        {
            context.Response.End();
        }
        SaveFile();
    }

    /// <summary>
    /// 文件保存操作
    /// </summary>
    /// <param name="basePath"></param>
    private void SaveFile(string basePath = "/upload/")
    {
        string _datePath = DateTime.Now.ToString("yyyyMMdd") + "/";
        basePath += _datePath;

        string serverPath = "~" + basePath;
        var name = string.Empty;
        serverPath = (serverPath.IndexOf("~") > -1) ? System.Web.HttpContext.Current.Server.MapPath(serverPath) :
        serverPath;
        if (!Directory.Exists(serverPath))
            Directory.CreateDirectory(serverPath);
        Random rand = new Random(24 * (int)DateTime.Now.Ticks);
        var ranNumber = rand.Next();
        name = ranNumber + ".jpg";
        //var _base64 = System.Web.HttpContext.Current.Request["_base64"];
        //if (!string.IsNullOrEmpty(_base64))
        //    Base64StrToImage(_base64,serverPath,ranNumber.ToString());

        var base64 = System.Web.HttpContext.Current.Request["_base64"];
        base64 = base64.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
        byte[] bytes = Convert.FromBase64String(base64);
        MemoryStream memStream = new MemoryStream(bytes);
        Image mImage = Image.FromStream(memStream);

        Bitmap bp = new Bitmap(mImage);
        MemoryStream ms = new MemoryStream();


        bp.Save(serverPath + name, System.Drawing.Imaging.ImageFormat.Jpeg);

        var _result = "{\"jsonrpc\" : \"2.0\", \"result\" : null, \"id\" : \"" + basePath + name + "\"}";
        System.Web.HttpContext.Current.Response.Write(_result);
    }

    /// <summary>
    /// 将Base64字符串转换为Image对象
    /// </summary>
    /// <param name="base64Str">base64字符串</param>
    /// <returns></returns>
    public static Bitmap Base64StrToImage(string base64Str)
    {
        Bitmap bitmap = null;

        try
        {
            byte[] arr = Convert.FromBase64String(base64Str);
            MemoryStream ms = new MemoryStream(arr);
            Bitmap bmp = new Bitmap(ms);

            Image mImage = Image.FromStream(ms);
            ms.Close();
            bitmap = bmp;
        }
        catch (Exception ex)
        {
        }

        return bitmap;
    }

    /// <summary>
    /// 将Base64字符串转换为图片并保存到本地
    /// </summary>
    /// <param name="base64Str">base64字符串</param>
    /// <param name="savePath">图片保存地址，如：/dis/Images/10000.png</param>
    /// <returns></returns>
    public static bool Base64StrToImage(string base64Str, string serverPath, string name)
    {
        var ret = true;

        try
        {
            var bitmap = Base64StrToImage(base64Str);

            if (bitmap != null)
            {
                //创建文件夹
                if (!Directory.Exists(serverPath.Replace("Up", "upload")))
                    Directory.CreateDirectory(serverPath);

                //图片后缀格式
                var suffix = serverPath.Substring(serverPath.LastIndexOf('.') + 1, serverPath.Length - serverPath.LastIndexOf('.') - 1).ToLower();
                //var suffixName = suffix == "png" ? ImageFormat.Png :
                //    suffix == "jpg" || suffix == "jpeg" ? ImageFormat.Jpeg :
                //    suffix == "bmp" ? ImageFormat.Bmp :
                //    suffix == "gif" ? ImageFormat.Gif : ImageFormat.Jpeg;

                //这里复制一份对图像进行保存，否则会出现“GDI+ 中发生一般性错误”的错误提示
                var bmpNew = new Bitmap(bitmap);
                var full = serverPath + name;
                bmpNew.Save(full);
                bmpNew.Dispose();

                bitmap.Dispose();
            }
            else
            {
                ret = false;
            }
        }
        catch (Exception ex)
        {
            ret = false;
        }

        return ret;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}